<?php

namespace App\Http\Controllers\Home;


use App\Model\Comcheckdetaillog;
use App\Model\Comwordslog;
use Illuminate\Support\Facades\Auth;
use PhpOffice\PhpWord\TemplateProcessor;

use App\Http\Controllers\Controller;

use App\Model\Checkgroup;
use App\Model\Checknegative;
use App\Model\Checkaccord;
use App\Model\Checkcommand;
use App\Model\Company;
use App\Model\Comcheck;
use App\Model\Comcheckdetail;
use App\Model\Checkentry;
use App\Model\Comcheckstep;
use App\Model\Comcheckgroup;
use App\Model\Area;
use App\Model\Comsafeofficer;
use App\Model\Commanager;
use App\User;
use App\Services\ImageClass;
use App\Model\Commondata;
use App\Services\Export\WordChoose;

use App\Services\WordcheckdataClass;

use Illuminate\Http\Request;
use App\Http\Requests\CheckRequest;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;

class NinecheckController extends Controller
{
    //选择人物环管
    public function choose(Request $request,int $status) {
        if($status > 4 || $status < 1) {
            \Session::flash('error', '参数错误!');
            return back();
        }
        $statusArray = [
            '1'=>'人的不安全行为',
            '2'=>'物的不安全状态',
            '3'=>'作业环境的缺陷',
            '4'=>'安全管理的缺陷',
        ];
        $title = $statusArray[$status];
        $request->session()->put('status',$status);
        $checkId = $request->session()->get('checkId',0);
        $type = $request->session()->get('firetype',0);
        $categoryId = $request->session()->get('categoryId',0);
        $where = ['categoryId'=>$categoryId,'status'=>$status,'type'=>$type];
        $comcheckgroup = new Comcheckgroup();
        $groups = $comcheckgroup->getCheckgroup($checkId,$categoryId,$status,$type);
        return view('ninecheck/choose')
            ->with('title',$title)
            ->with('type',$type)
            ->with('groups',$groups)
            ->with('status',$status);
    }

    //新增检查项
    public function creategroup(Request $request)
    {
        $firetype = $request->session()->get('firetype',0);

        $groups = $request->input('group');
        $status = $request->input('status');
//        dd($request->input());
        $companyId = $request->session()->get('companyId');
        if(!$firetype || !$companyId) {
            \Session::flash('error', '参数错误!');
            return back();
        }
        $comcheckInfo = Comcheck::where(['companyId'=>$companyId])->select('id','status')->first();
        if($comcheckInfo) {
            $checkId = $comcheckInfo['id'];
        } else {
            $user = Auth::user();
            $check['companyId'] = $companyId;
            $check['created'] = date('Y-m-d H:i:s',time());
            $check['userId'] = $user->id;
            $checkId = Comcheck::insertGetId($check);
        }

//        if($groups) {
//            foreach ($groups as $k => $v) {
//                $groups[$k]['checkId'] = $checkId;
//            }
//            Comcheckgroup::insert($groups);
//        }

        $step = [];
        $step['checkId'] = $checkId;
        $step['stepStatus'] = $status;
        $step['typeStatus'] = $firetype;
        $one = Comcheckstep::where(['checkId'=>$step['checkId'],'stepStatus'=>$step['stepStatus'],'typeStatus'=>$step['typeStatus']])->get();
        $one = json_decode(json_encode($one), true);
        if (empty($one)){Comcheckstep::insertGetId($step);}
        $checkStep = Comcheckstep::where(['checkId'=>$checkId,'typeStatus'=>$firetype])->get();
        $stepArray = ['1'=>1,'2'=>2,'3'=>3,'4'=>4];
        foreach ($checkStep as $k => $v) {
            unset($stepArray[$v->stepStatus]);
        }
        if(count($stepArray)) {
            foreach ($stepArray as $k) {
                return redirect('ninecheck/choose/'.$k);
            }
        } else {
            return redirect('ninesmall/choose/'.$firetype);
        }


    }

    public function finish(int $companyId)
    {
        $fire = 0;
        $nofire = 0;
        $comcheckstep = new Comcheckstep();
        $fireinfo = $comcheckstep->getfiretype($companyId);
        if(count($fireinfo)){
            foreach ($fireinfo as $k => $v) {
                if($v->typeStatus == 1) {
                    $fire += $v->stepStatus;
                }
                if($v->typeStatus == 2) {
                    $nofire += $v->stepStatus;
                }
            }
        }
        $company = Company::find($companyId);
        if(!$company) {
            \Session::flash('error', '公司信息有误!');
            return redirect('/ninesmall/firetype/'.$companyId);
        }
        /**新增**/
        $comcheck = new Comcheck();
        $checkinfo = $comcheck->where(['companyId'=>$companyId])->first();
        $checkdetaillog = Comcheckdetaillog::where('checkId','=',$checkinfo->id)->orderBy('created_at','desc')->first();
//        $checkdetaillog = json_decode(json_encode($checkdetaillog), true);
//        if (!empty($yes)){
        if (!empty($checkdetaillog->created_at)){
            $yes =strtotime($checkdetaillog->created_at)>($checkinfo->wordsTime)?true:false;
        }else{
            $yes = false;
        }
        $comcheckupdate = Comcheck::where('id','=',$checkinfo->id)->first();
        if (!empty($comcheckupdate->updated)){
            $insert =$comcheckupdate->updated>($checkinfo->wordsTime)?true:false;
        }else{
            $insert = false;
        }
        if (!$yes && !$insert)
        {
            $yess = true;
        }else{
            $yess = false;

        }
        /**新增**/
        if($company['schedule'] >= 2 && $yess) {
//            dd('ss');
            return redirect('/ninecheck/download/'.$companyId);
        }
        //获取初查隐患
        $detail = new Comcheckdetail();
//        dd($checkinfo->id);
//        $comcheck = Comcheck::find($id);
        $infos = $detail->getInconform($checkinfo->id);
        $negatives = [];
        foreach ($infos as $k=>$v){
            if (!empty($v->negatives)){
                $arr = explode(',',$v->negatives);
                foreach ($arr as $ar){
                    if (!empty($ar)){
                        array_push($negatives,$ar);
                    }
                }
            }
        }
        $negatives = Checknegative::whereIn('id',$negatives)->get();
        return view('ninecheck/finish')
            ->with('negatives',$negatives)
            ->with('companyId',$companyId);
    }



    //查看风险点
    public function show(Request $request,$groupId) {
        ////导航/////
        $companyId = $request->session()->get('companyId',0);
        $company = Company::find($companyId);
        $fire = 0;
        $nofire = 0;        $zhijian = 0;
        $comcheckstep = new Comcheckstep();
        $fireinfo = $comcheckstep->getfiretype($companyId);
        if(count($fireinfo)){
            foreach ($fireinfo as $k => $v) {
                if($v->typeStatus == 1) {
                    $fire += $v->stepStatus;
                }
                if($v->typeStatus == 2) {
                    $nofire += $v->stepStatus;
                }
                if($v->typeStatus == 5) {
                    $zhijian += $v->stepStatus;
                }
            }
        }
        $comcheckInfo = Comcheck::where(['companyId'=>$companyId])->select('id','status')->first();
        $categoryId = $request->session()->get('categoryId',0);
        $comcheckstep = new Comcheckstep();
        $fireinfo = $comcheckstep->getfiretype($companyId);
        $steps = [
            '1'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>1])->first()->id,
                'status' => 0,
                'type' => 1,
                'title'=>'基础档案'
            ],
            '2'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>1])->first()->id,
                'status' => 0,
                'type' => 1,
                'title'=>'作业现场'
            ],
            '3'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>2])->first()->id,
                'status' => 0,
                'type' => 2,
                'title'=>'基础档案'
            ],
            '4'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>2])->first()->id,
                'status' => 0,
                'type' => 2,
                'title'=>'作业现场'
            ],
            '5'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>5])->first()->id,
                'status' => 0,
                'type' => 5,
                'title'=>'基础档案'
            ],
            '6'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>5])->first()->id,
                'status' => 0,
                'type' => 5,
                'title'=>'作业现场'
            ],
        ];
        if(count($fireinfo)){
            foreach ($fireinfo as $k => $v) {
                if($v->typeStatus == 1) {
                    $steps[$v->stepStatus]['status'] = 1 ;
                }
                if($v->typeStatus == 2 && $v->stepStatus == 1) {
                    $steps[3]['status'] = 1 ;
                }
                if($v->typeStatus == 2 && $v->stepStatus == 2) {
                    $steps[4]['status'] = 1 ;
                }
                if($v->typeStatus == 5 && $v->stepStatus == 1) {
                    $steps[5]['status'] = 1 ;
                }
                if($v->typeStatus == 5 && $v->stepStatus == 2) {
                    $steps[6]['status'] = 1 ;
                }
            }
        }
        ////导航/////
        $groupInfo = Checkgroup::find($groupId);
        $is = $groupInfo->status;
        $type = $groupInfo->type;
        $title = $is==1?'基础档案':'作业现场';
        $entrys = Checkentry::where('groupId',$groupId)->get();
        return view('ninecheck/show')
            ->with('groupId',$groupId)
            ->with('title',$title)
            ->with('is',$is)
            ->with('companyId',$companyId)
            ->with('type',$type)
            ->with('entrys',$entrys)
            ->with('fire',$fire)
            ->with('zhijian',$zhijian)
            ->with('steps',$steps)
            ->with('nofire',$nofire);
    }


    //查看其他
    public function showelse($groupId) {
        $groupInfo = Checkgroup::find($groupId);

        if(empty($groupInfo)){
            return back();
        }
        $title = $groupInfo->name;
        $entrys = Checkentry::where('groupId',$groupId)->get();
        return view('ninecheck/showelse')
            ->with('groupId',$groupId)
            ->with('title',$title)
            ->with('entrys',$entrys);
    }


    //检查项的提交
    public function create(CheckRequest $request) {
        $data = $request->all();
        $groupId = $request->input('groupId');
        $checkId = $request->session()->get('checkId',0);
        $companyId = $request->session()->get('companyId',0);
        if(!$checkId)
        {
            return redirect('/ninesmall');
        }
        $entryIds = $data['entryId'];
        $statuses = $data['status'];
        $isfires = $data['isfire'];
        if (!empty($data['content'])){
            $contents = $data['content'];}
        else{$contents = [];}
        $contentsexist = $data['contentexist'];
        $pictures = is_array($data['picture'])?$data['picture']:0;
        $negatives = isset($data['negative'])?$data['negative']:0;
        foreach ($entryIds as $k => $v) {
            $checkdetail[$k]['checkId'] = $checkId;
            $checkdetail[$k]['entryId'] = $v;
            $checkdetail[$k]['pictures'] = '';
            $checkdetail[$k]['groupId'] = $groupId;
        }
        foreach ($statuses as $k => $v) {
            $checkdetail[$k]['status'] = $v;
            if (!empty($contentsexist[$k])){
                $checkdetail[$k]['status'] = 2;
            }
        }
//        foreach ($contents as $k => $v) {
//            $checkdetail[$k]['content'] = $v;
//        }
        foreach ($isfires as $k => $v) {
            $checkdetail[$k]['isfire'] = $v;
        }
        foreach ($contentsexist as $k => $v) {
            $checkdetail[$k]['contentexist'] = $v;
        }
        if($pictures) {
            foreach ($pictures as $k => $v) {
                $checkdetail[$k]['pictures'] = $v;
            }
        }
        foreach ($checkdetail as $k => $v) {
            $checkdetail[$k]['negatives'] = '';
            if($negatives) {
                foreach ($negatives as $kk => $vv) {
                    if($v['entryId'] == $kk){
                        $checkdetail[$k]['negatives'] = $vv;
                    }
                }
            }
            foreach ($contents as $key => $va) {
                $str = '';
                if (is_array($va)){
                    foreach ($va as $va1){
                        if (!is_numeric($va1)){
                            $str .= $va1;
                            $str .= ';';
                        }
                    }
                    if ($key == $v['entryId']){
                        $checkdetail[$k]['content'] = $str;
                    }
                }else{
                    if ($key == $v['entryId']) {
                        $checkdetail[$k]['content'] = $va;

                    }
                }
            }
        }
        $firetype = Checkgroup::find($groupId)->type;
//        dd($checkdetail);
        $comCheckdetail = new Comcheckdetail();
        foreach ($checkdetail as $k=>$v){
            if($v['isfire'] == 0){
                $one = Comcheckdetail::where(['checkId'=>$v['checkId'],'groupId'=>$v['groupId'],'entryId'=>$v['entryId']])->get();
                $one = json_decode(json_encode($one), true);
                if (empty($one)){
                    Comcheckdetail::insert($v);}
            }else{
                Comcheckdetail::insert($v);
            }
//            }else{
//                return redirect('ninesmall/choose/'.$firetype);
//            }
        }
//        $comCheckdetail->addAll($checkdetail);
        Comcheck::where('id','=',$checkId)->update(['updated'=>time()]);
        $status = Checkgroup::find($groupId)->status;
        $step = [];
        $step['checkId'] = $checkId;
        $step['stepStatus'] = $status;
        $step['typeStatus'] = $firetype;
        $one = Comcheckstep::where(['checkId'=>$step['checkId'],'stepStatus'=>$step['stepStatus'],'typeStatus'=>$step['typeStatus']])->get();
        $one = json_decode(json_encode($one), true);
        if (empty($one)){Comcheckstep::insertGetId($step);}
        if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){
            return json_encode(['data'=>'success']);
            // ajax 请求的处理方式
        }else{
            return redirect('ninesmall/firetype/'.$companyId);
        }
        // $this->exportWord1($checkId);
    }


    //其他检查项的提交
    public function createelse(CheckRequest $request) {
        $data = $request->all();
        $groupId = $request->input('groupId');
        $checkId = $request->session()->get('checkId',0);
        $status = $request->session()->get('status',0);
        $contents = $data['content'];
        $pictures = is_array($data['picture'])?$data['picture']:0;
        foreach ($contents as $k => $v) {
            $checkdetail[$k]['checkId'] = $checkId;
            $checkdetail[$k]['groupId'] = $groupId;
            $checkdetail[$k]['content'] = $v;
            if (empty($v)){
                $checkdetail[$k]['status'] = 1;
            }else{
                $checkdetail[$k]['status'] = 2;
            }
        }
        if($pictures) {
            foreach ($pictures as $k => $v) {
                $checkdetail[$k]['pictures'] = $v;
            }
        }
        $checkgroup['checkId'] = $checkId;
        $checkgroup['groupId'] = $groupId;
        $checkgroup['status'] = 1;
        /*使用事务插入*/
        DB::beginTransaction();
        try{
            $insert = Comcheckgroup::insertGetId($checkgroup);
            if($insert) {
                DB::commit();
            }
        }catch (\Exception $e) {
            DB::rollBack();
//            \Session::flash('error', $e->getMessage());
            return redirect('ninecheck/choose/'.$status);
        }
        $comCheckdetail = new Comcheckdetail();
        $comCheckdetail->addAll($checkdetail);
        // $this->exportWord1($checkId);
        return redirect('ninecheck/choose/'.$status);
    }


    public function update(Request $request,int $groupId){
        ////导航/////
        $companyId = $request->session()->get('companyId',0);
        $company = Company::find($companyId);
        $fire = 0;
        $nofire = 0;$zhijian = 0;
        $comcheckstep = new Comcheckstep();
        $fireinfo = $comcheckstep->getfiretype($companyId);
        if(count($fireinfo)){
            foreach ($fireinfo as $k => $v) {
                if($v->typeStatus == 1) {
                    $fire += $v->stepStatus;
                }
                if($v->typeStatus == 2) {
                    $nofire += $v->stepStatus;
                }
                if($v->typeStatus == 5) {
                    $zhijian += $v->stepStatus;
                }
            }
        }
        $comcheckInfo = Comcheck::where(['companyId'=>$companyId])->select('id','status')->first();
        $categoryId = $request->session()->get('categoryId',0);
        $comcheckstep = new Comcheckstep();
        $fireinfo = $comcheckstep->getfiretype($companyId);
        $steps = [
            '1'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>1])->first()->id,
                'status' => 0,
                'type' => 1,
                'title'=>'基础档案'
            ],
            '2'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>1])->first()->id,
                'status' => 0,
                'type' => 1,
                'title'=>'作业现场'
            ],
            '3'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>2])->first()->id,
                'status' => 0,
                'type' => 2,
                'title'=>'基础档案'
            ],
            '4'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>2])->first()->id,
                'status' => 0,
                'type' => 2,
                'title'=>'作业现场'
            ],
            '5'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>5])->first()->id,
                'status' => 0,
                'type' => 5,
                'title'=>'基础档案'
            ],
            '6'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>5])->first()->id,
                'status' => 0,
                'type' => 5,
                'title'=>'作业现场'
            ],
        ];
        if(count($fireinfo)){
            foreach ($fireinfo as $k => $v) {
                if($v->typeStatus == 1) {
                    $steps[$v->stepStatus]['status'] = 1 ;
                }
                if($v->typeStatus == 2 && $v->stepStatus == 1) {
                    $steps[3]['status'] = 1 ;
                }
                if($v->typeStatus == 2 && $v->stepStatus == 2) {
                    $steps[4]['status'] = 1 ;
                }

                if($v->typeStatus == 5 && $v->stepStatus == 1) {
                    $steps[5]['status'] = 1 ;
                }
                if($v->typeStatus == 5 && $v->stepStatus == 2) {
                    $steps[6]['status'] = 1 ;
                }
            }
        }
        ////导航/////
        $checkId = $request->session()->get('checkId',0);
        $data = Comcheckdetail::where(['checkId'=>$checkId,'groupId'=>$groupId])->get();
        $negatives = [];
        foreach ($data as $v){
            $arr = explode(",",$v->negatives);
            foreach ($arr as $v1){
                empty($v1)?'':array_push($negatives,$v1);
            }
        }
        $negatives = Checknegative::whereIn('id',$negatives)->get();

        $groupInfo = Checkgroup::find($groupId);
        if(empty($groupInfo)){
            return back();
        }
        $is = $groupInfo->status;

        $comcheckgroup = [];
        $comcheckgroup = Comcheckgroup::where(['checkId'=>$checkId,'groupId'=>$groupId])->first();
        $entrys = Checkentry::where('groupId',$groupId)->get();
        $title = $is==1?'基础档案':'作业现场';
        $type = $groupInfo->type;
        return view('ninecheck/update')
            ->with('data',$data)
            ->with('groupId',$groupId)
            ->with('entrys',$entrys)
            ->with('comcheckgroup',$comcheckgroup)
            ->with('negatives',$negatives)
            ->with('type',$type)
            ->with('companyId',$companyId)
            ->with('title',$title)
            ->with('fire',$fire)
            ->with('zhijian',$zhijian)
            ->with('steps',$steps)
            ->with('nofire',$nofire);

    }
    public function updateelse(Request $request,int $groupId){
        $checkId = $request->session()->get('checkId',0);
        $data = Comcheckdetail::where(['checkId'=>$checkId,'groupId'=>$groupId])->get();
//        $data = json_decode(json_encode($data), true);
//        dd($data);
        $negatives = [];
        foreach ($data as $v){
            $arr = explode(",",$v->negatives);
            foreach ($arr as $v1){
                empty($v1)?'':array_push($negatives,$v1);
            }
        }
        $negatives = Checknegative::whereIn('id',$negatives)->get();

        $groupInfo = Checkgroup::find($groupId);
        if(empty($groupInfo)){
            return back();
        }
        $comcheckgroup = [];
        $comcheckgroup = Comcheckgroup::where(['checkId'=>$checkId,'groupId'=>$groupId])->first();
        $entrys = Checkentry::where('groupId',$groupId)->get();
        $title = $groupInfo->name;
        $ren= $comcheckgroup->ren;$caichan=$comcheckgroup->cai;$des = $comcheckgroup->des;
        return view('ninecheck/updateelse')
            ->with('data',$data)
            ->with('groupId',$groupId)
            ->with('entrys',$entrys)
            ->with('ren',$ren)
            ->with('caichan',$caichan)
            ->with('des',$des)
            ->with('comcheckgroup',$comcheckgroup)
            ->with('negatives',$negatives)
            ->with('title',$title);

    }
    public function updatepost(Request $request){
        $data = $request->all();
//        dd($data);
        $groupId = $request->input('groupId');
        $firetype = Checkgroup::find($groupId)->type;
        $checkId = $request->session()->get('checkId',0);
        $companyId = $request->session()->get('companyId',0);
        $status = $request->session()->get('status',0);
        if(!$checkId)
        {
            return redirect('/ninesmall');
        }
        $entryIds = $data['entryId'];
        $ids = $data['id'];
        $statuses = $data['status'];
        if (!empty($data['content'])){
            $contents = $data['content'];}
        else{$contents = [];}
        $contentsexist = $data['contentexist'];
        $pictures = is_array($data['picture'])?$data['picture']:0;
        $negatives = isset($data['negative'])?$data['negative']:0;
        foreach ($entryIds as $k => $v) {
            $checkdetail[$k]['id'] = $ids[$k];
            $checkdetail[$k]['checkId'] = $checkId;
            $checkdetail[$k]['entryId'] = $v;
            $checkdetail[$k]['pictures'] = '';
            $checkdetail[$k]['groupId'] = $groupId;
        }
        foreach ($statuses as $k => $v) {
            $checkdetail[$k]['status'] = $v;
//            if (empty($contentsexist[$k]) && empty($entryIds[$k])){
//                $checkdetail[$k]['status'] = 1;
//            }
            if (!empty($contentsexist[$k]) && empty($entryIds[$k])){
                $checkdetail[$k]['status'] = 2;
            }
            if (empty($contentsexist[$k]) && empty($entryIds[$k])){
                $checkdetail[$k]['status'] = 1;
            }
        }
//        foreach ($contents as $k => $v) {
//            $checkdetail[$k]['content'] = $v;
//        }
        foreach ($contentsexist as $k => $v) {
            $checkdetail[$k]['contentexist'] = $v;
        }
        if($pictures) {
            foreach ($pictures as $k => $v) {
                if (empty($v)){
                    $detail = Comcheckdetail::where('id','=',$ids[$k])->get();
                    $detail = json_decode(json_encode($detail), true);
                    $checkdetail[$k]['pictures'] = $detail[0]['pictures'];
                }else{
                    $checkdetail[$k]['pictures'] = $v;
                }
            }
        }
        foreach ($checkdetail as $k => $v) {
            $checkdetail[$k]['negatives'] = '';
            if($negatives) {
                foreach ($negatives as $kk => $vv) {
                    if($v['entryId'] == $kk){
                        $checkdetail[$k]['negatives'] = $vv;
                    }
                }
            }
            foreach ($contents as $key => $va) {
                if ($v['entryId'] == $key) {
                    $str = '';
                    if (is_array($va)) {
                        foreach ($va as $va1) {
                            if (!is_numeric($va1)) {
                                $str .= $va1;
                                $str .= ';';
                            }
                        }
                        if ($key == $v['entryId']) {
                            $checkdetail[$k]['content'] = $str;
                        }
                    } else {
                        $checkdetail[$k]['content'] = $va;

                    }
                }
            }
        }
        Comcheck::where('id','=',$checkId)->update(['updated'=>time()]);
        $time = time();
        foreach ($checkdetail as $v){
            $result = Comcheckdetail::where('id','=',$v['id'])->update($v);
            $old = Comcheckdetail::where('id','=',$v['id'])->get();
            $old = json_decode(json_encode($old), true);
            $old[0]['created_at'] = $time;
            $comCheckdetaillog = new Comcheckdetaillog();
            if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){
                // ajax 请求的处理方式
            }else{
                $comCheckdetaillog->addAll($old[0]);
            }
        }
        if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){
            return json_encode(['data'=>'success']);
            // ajax 请求的处理方式
        }else{
            return redirect('ninesmall/firetype/'.$companyId);}
    }


    public function updateelsepost(Request $request){
        $data = $request->all();
        $groupId = $request->input('groupId');
        $ids = $request->input('id');
        $checkId = $request->session()->get('checkId',0);
        $status = $request->session()->get('status',0);
        $contents = $data['content'];
        $pictures = is_array($data['picture'])?$data['picture']:0;
        foreach ($contents as $k => $v) {
            $checkdetail[$k]['checkId'] = $checkId;
            $checkdetail[$k]['id'] = $ids[$k];
            $checkdetail[$k]['groupId'] = $groupId;
            $checkdetail[$k]['content'] = $v;
            if (empty($v)){
                $checkdetail[$k]['status'] = 1;
            }else{
                $checkdetail[$k]['status'] = 2;
            }
        }
        if($pictures) {
            foreach ($pictures as $k => $v) {
                if (empty($v)){
                    $detail = Comcheckdetail::where('id','=',$ids[$k])->get();
                    $detail = json_decode(json_encode($detail), true);
                    $checkdetail[$k]['pictures'] = $detail[0]['pictures'];
                }else{
                    $checkdetail[$k]['pictures'] = $v;
                }
            }
        }
        Comcheck::where('id','=',$checkId)->update(['updated'=>time()]);
        $time = time();
        foreach ($checkdetail as $v){
            $result = Comcheckdetail::where('id','=',$v['id'])->update($v);
            $old = Comcheckdetail::where('id','=',$v['id'])->get();
            $old = json_decode(json_encode($old), true);
            $old[0]['created_at'] = $time;
            $comCheckdetaillog = new Comcheckdetaillog();
            $comCheckdetaillog->addAll($old[0]);
        }
        return redirect('ninecheck/choose/'.$status);
    }


    public function signature(Request $request)
    {
        $companyId = $request->input('companyId');
        $comcheckInfo = Comcheck::where(['companyId'=>$companyId])->select('id','status')->first();
        if(!$comcheckInfo) {
            return redirect('/ninesmall/firetype/'.$companyId);
        }
        $lng = $request->input('lng')?:'120.370839';
        $lat = $request->input('lat')?:'36.128151';
        $userimgbase=$request->input('userimgbase');
        $comimgbase=$request->input('comimgbase');
        if(empty($userimgbase) || empty($comimgbase)) {
            \Session::flash('error', '未签名!');
            return back();
        }
        $imgclass = new ImageClass();
        $usersignature = $imgclass->base64toimg($userimgbase);
        $comsignature = $imgclass->base64toimg($comimgbase);
        $wancheng = Company::where(['id'=>$companyId])->first();
        $mapimg = $imgclass->maptoimg($lng,$lat,$wancheng->comName);
        $update = [
            'comsignature'=>$comsignature,
            'usersignature'=>$usersignature,
            'lng'=>$lng,
            'lat'=>$lat,
            'mapimg'=>$mapimg,
        ];
        Comcheck::where(['companyId'=>$companyId])->update($update);
        $wancheng = Company::where(['id'=>$companyId])->first();
        if ($wancheng->schedule >=2){

        }else{
            Company::where(['id'=>$companyId])->update(['schedule'=>2]);
        }

        return redirect('ninecheck/download/'.$companyId);
    }
    public function downloadwords(int $companyId)
    {
        // $wordsUrl = $this->exportWord($companyId);
        $comcheck = new Comcheck();
        $comCheckdetail = new Comcheckdetail();
        $checkinfo = $comcheck->where(['companyId'=>$companyId])->first();
        $download = [];
        $wordsUrl = $checkinfo->wordsUrl;
        $checkdetaillog = Comcheckdetaillog::where('checkId','=',$checkinfo->id)->orderBy('created_at','desc')->first();

        if (!empty($checkdetaillog->created_at)){
            $yes =strtotime($checkdetaillog->created_at)>($checkinfo->wordsTime)?true:false;
        }else{
            $yes = false;
        }
//        if(!$wordsUrl || $yes) {
//            $wordsUrl = $this->exportWord($companyId);
//            /***新增***/
//            $checkinfo->wordsUrl = $wordsUrl;
//            $checkinfo->wordsTime = time();
//
//            /***新增***/
//            $checkinfo->save();
//            $log = [];
//            $log['checkId'] = $checkinfo->id;
//            $log['wordUrl'] = $checkinfo->wordsUrl;
//            $log['comsignature'] = $checkinfo->comsignature;
//            $log['usersignature'] = $checkinfo->usersignature;
//            $log['created'] = time();
//            $result = Comwordslog::insert($log);
//        }
        $urlArray = explode(',', $wordsUrl);
        foreach ($urlArray as $k => $v) {
            $download[$k]['name'] = substr(strrchr($v,'/'),1,-18);
            $download[$k]['url'] = substr($v,1);
        }
        return view('ninecheck/download')
            ->with('download',$download);
    }

    public function download(int $companyId)
    {
        // $wordsUrl = $this->exportWord($companyId);
        $comcheck = new Comcheck();
        $comCheckdetail = new Comcheckdetail();
        $checkinfo = $comcheck->where(['companyId'=>$companyId])->first();
        $download = [];
        $wordsUrl = $checkinfo->wordsUrl;
        $checkdetaillog = Comcheckdetaillog::where('checkId','=',$checkinfo->id)->orderBy('created_at','desc')->first();

        if (!empty($checkdetaillog->created_at)){
            $yes =strtotime($checkdetaillog->created_at)>($checkinfo->wordsTime)?true:false;
        }else{
            $yes = false;
        }
        $comcheckupdate = Comcheck::where('id','=',$checkinfo->id)->first();
        if (!empty($comcheckupdate->updated)){
            $insert =$comcheckupdate->updated>($checkinfo->wordsTime)?true:false;
        }else{
            $insert = false;
        }
        if ($yes || $insert)
        {
            $yess = true;
        }else{
            $yess = false;

        }
//        dd($yess);
        if(!$wordsUrl || $yess) {
            $wordsUrl = $this->exportWord($companyId);
            /***新增***/
            $checkinfo->wordsUrl = $wordsUrl;
            $checkinfo->wordsTime = time();

            /***新增***/
            $checkinfo->save();
            $log = [];
            $log['checkId'] = $checkinfo->id;
            $log['wordUrl'] = $checkinfo->wordsUrl;
            $log['comsignature'] = $checkinfo->comsignature;
            $log['usersignature'] = $checkinfo->usersignature;
            $log['created'] = time();
            $result = Comwordslog::insert($log);
        }
        $urlArray = explode(',', $wordsUrl);
        foreach ($urlArray as $k => $v) {
            $download[$k]['name'] = substr(strrchr($v,'/'),1,-18);
            $download[$k]['url'] = substr($v,1);
        }
        return view('ninecheck/download')
            ->with('download',$download);
    }
    /**
     * 生成检测报告
     *
     **/
    protected function exportWord($companyId)
    {
        $company = Company::find($companyId);
        /*主要负责人*/
        $manager = Commanager::where('companyId', $company->id)->first();
        /*安全负责人*/
        $safeUser = Comsafeofficer::where('companyId', $company->id)->first();
        //检查情况
        $comcheck = new Comcheck();
        $checkinfo = $comcheck->where(['companyId'=>$companyId])->first();
        /*初查检查人员*/
        $checkUser = User::where('id', $checkinfo->userId)->first();
        //负面清单
        $comCheckdetail = new Comcheckdetail();
        $checkdetail = $comCheckdetail->getCheckDetail($companyId);
        //法律依据
        $accordObj = new Checkaccord();
        $checkAccords = $accordObj->getAccordByCheckId($checkinfo->id);

        $comName = $company->comName;
        $created = date('Ymdhi',strtotime($checkinfo->created));
        $address = [];
        $address['province'] = Area::find($company->province)->name;
        $address['city'] = Area::find($company->city)->name;
        $address['district'] = Area::find($company->district)->name;
        $address['street'] = Area::find($company->street)->name;

        //数据整理
        $checkDataClass = new WordcheckdataClass();
        $wordData = $checkDataClass->createNotice($company,$checkinfo,$checkdetail,$address,$checkUser,$manager);
        $fireData = $wordData['data'];
        $fireData = array_merge($fireData,$wordData['fire']);
        $imgData = $wordData['imgData'];
        $productData = $wordData['data'];
        $productData = array_merge($productData, $wordData['product']);
        //生成隐患告知单
        $fireTemplateProcessor =  new TemplateProcessor('./word/消防安全事故隐患告知单-初查.docx');
        $unfireTemplateProcessor = new TemplateProcessor('./word/生产安全事故隐患告知单-初查.docx');
        $fireDocName = $comName.'消防安全事故隐患告知单_' . $created;
        $unfireDocName = $comName.'生产安全事故隐患告知单_' . $created;
        $fireWordClass = WordChoose::choose($fireTemplateProcessor,'notice');
        $unfireWordClass = WordChoose::choose($unfireTemplateProcessor,'notice');
        $fireWordClass->set($fireData,$imgData);
        $unfireWordClass->set($productData, $imgData);
        $fireNoticeUrl = $fireWordClass->create(date('Ymd', time()),$fireDocName);
        $unfireNoticeUrl = $unfireWordClass->create(date('Ymd', time()), $unfireDocName);
        //检查表
        $fireCheckProcessor =  new TemplateProcessor('./word/消防安全检查记录表-初查.docx');
        $unfireCheckProcessor = new TemplateProcessor('./word/生产安全检查记录表-初查.docx');
        $fireDocName = $comName.'消防安全检查记录表_' . $created;
        $unfireDocName = $comName.'生产安全检查记录表_' . $created;
        /*导出word*/
        $exportData = $checkDataClass->createRecord($company,$checkinfo,$checkdetail,$checkUser, $address, $safeUser,$checkAccords);

        $exportFireBasicData = $exportData['exportLogData'];
        $exportFireBasicData = array_merge($exportFireBasicData, $exportData['exportFireNum']);
        $exportFireLogData = $exportData['exportFireLogData'];

        $exportUnFireBasicData = $exportData['exportLogData'];
        $exportUnFireBasicData = array_merge($exportUnFireBasicData, $exportData['exportUnfireNum']);
        $exportUnFireLogData = $exportData['exportUnFireLogData'];

        $fireWordClass = WordChoose::choose($fireCheckProcessor,'nineCheckAgainLog');
        $fireWordClass->set($exportFireBasicData, $exportFireLogData);
        $fireWordUrl = $fireWordClass->create(date('Ymd', time()),$fireDocName);
        $unfireWordClass = WordChoose::choose($unfireCheckProcessor,'nineCheckAgainLog');
        $unfireWordClass->set($exportUnFireBasicData, $exportUnFireLogData);
        $unfireWordUrl = $unfireWordClass->create(date('Ymd', time()),$unfireDocName);

        /*生成基础档案*/

        $checkDataClass = new WordcheckdataClass();
        $archivesWordData = $checkDataClass->createArchives($company,$safeUser,$manager,$address,$checkinfo,$checkdetail,$checkUser,$checkAccords);
        $returnImg = $checkDataClass->generateImg($checkdetail);
        $archivesWordData['imgData'] = array_merge($archivesWordData['imgData'], $returnImg);
        $archivesProcessor =  new TemplateProcessor('./word/安全检查档案-初查.docx');
        $archivesDocName = $comName.'安全检查档案_' . $created;
        $archivesWordClass = WordChoose::choose($archivesProcessor,'archives');
        $archivesWordClass->set($archivesWordData['basicData'], $archivesWordData['imgData'], $archivesWordData['record']);
        $archivesWordUrl = $archivesWordClass->create(date('Ymd', time()),$archivesDocName);



        /*保存word文档路径*/
        $checkinfo->wordsUrl = $fireNoticeUrl.','.$unfireNoticeUrl.','.$fireWordUrl.','.$unfireWordUrl.','.$archivesWordUrl;

        return $checkinfo->wordsUrl;
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 查看重大隐患
     */
    public function showdanger() {
        $entrys = Checkentry::whereNull('groupId')->get();
        return view('ninecheck/showdanger')
            ->with('entrys',$entrys);
    }

    /**
     * @param CheckRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * 重大隐患提交
     */
    public function createdanger(CheckRequest $request) {
        $data = $request->all();
        $checkId = $request->session()->get('checkId',0);
        $companyId = $request->session()->get('companyId',0);
        if(!$checkId)
        {
            return redirect('/ninesmall');
        }
        $entryIds = $data['entryId'];
        $statuses = $data['status'];
        $contents = $data['content'];
        $pictures = is_array($data['picture'])?$data['picture']:0;
        foreach ($entryIds as $k => $v) {
            $checkdetail[$k]['checkId'] = $checkId;
            $checkdetail[$k]['entryId'] = $v;
            $checkdetail[$k]['pictures'] = '';
        }
        foreach ($statuses as $k => $v) {
            $checkdetail[$k]['status'] = $v;
            if (!empty($contents[$k])){
                $checkdetail[$k]['status'] = 2;
            }
        }
        foreach ($contents as $k => $v) {
            $checkdetail[$k]['content'] = $v;
        }
        if($pictures) {
            foreach ($pictures as $k => $v) {
                $checkdetail[$k]['pictures'] = $v;
            }
        }
        $comCheckdetail = new Comcheckdetail();
        $comCheckdetail->addAll($checkdetail);
        Comcheck::where('id','=',$checkId)->update(['updated'=>time()]);
        return redirect('ninesmall/firetype/'.$companyId);
    }

    /**
     * @param Request $request
     * @param int $checkId
     * @return mixed
     * 编辑重大隐患
     */
    public function updatedanger(Request $request,int $checkId){
        $data = Comcheckdetail::whereNull('groupId')->where(['checkId'=>$checkId])->get();
        $entrys = Checkentry::whereNull('groupId')->get();
        return view('ninecheck/updatedanger')
            ->with('data',$data)
            ->with('entrys',$entrys);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * 重大隐患编辑提交
     */
    public function updatepostdanger(Request $request){
        $data = $request->all();
        $entryIds = $data['entryId'];
        $ids = $data['id'];
        $statuses = $data['status'];
        $contents = $data['content'];
        $pictures = is_array($data['picture'])?$data['picture']:0;
        foreach ($entryIds as $k => $v) {
            $id = $ids[$k];
            $checkdetail[$k]['id'] = $ids[$k];
            $checkdetail[$k]['entryId'] = $v;
            $checkdetail[$k]['pictures'] = '';
        }
        $checkId = Comcheckdetail::find($id)->checkId;
        $companyId = Comcheck::find($checkId)->companyId;
        foreach ($statuses as $k => $v) {
            $checkdetail[$k]['status'] = $v;
        }
        foreach ($contents as $k => $v) {
            if ($checkdetail[$k]['status'] == 1){
                $checkdetail[$k]['content'] = '';
            }else{
                $checkdetail[$k]['content'] = $v;
            }
        }
        if($pictures) {
            foreach ($pictures as $k => $v) {
                if (empty($v)){
                    $detail = Comcheckdetail::where('id','=',$ids[$k])->get();
                    $detail = json_decode(json_encode($detail), true);
                    $checkdetail[$k]['pictures'] = $detail[0]['pictures'];
                }else{
                    $checkdetail[$k]['pictures'] = $v;
                }
            }
        }

        Comcheck::where('id','=',$checkId)->update(['updated'=>time()]);
        $time = time();
        foreach ($checkdetail as $v){
            $result = Comcheckdetail::where('id','=',$v['id'])->update($v);
            $old = Comcheckdetail::where('id','=',$v['id'])->get();
            $old = json_decode(json_encode($old), true);
            $old[0]['created_at'] = $time;
            $comCheckdetaillog = new Comcheckdetaillog();
            $comCheckdetaillog->addAll($old[0]);
        }
        return redirect('ninesmall/firetype/'.$companyId);
    }

}
